package com.oromwin.repos.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.logging.Log;

import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposConfig;
import com.oromwin.repos.server.thread.SocketThread;

public class ReposSocketServer extends Thread {
    private Log log = Logger.getLog(ReposSocketServer.class);
    private ServerSocket listener = null;
    private static boolean _shutdown = false;
    private transient static int _refCount = 0;
    private static Object _lockObject = new Object();

    public ReposSocketServer() {
        try {
            if (listener == null)
                listener = new ServerSocket(ReposConfig.getInstance().getReposSocketPort());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized static boolean isShutdown() {
        return _shutdown;
    }

    public synchronized static void setShutdown(boolean shutdown) {
        ReposSocketServer._shutdown = shutdown;
    }

    public synchronized static void incrementCount() {
        _refCount++;
    }

    public synchronized static void decrementCount() {
        _refCount--;
    }

    public synchronized static int getRefCount() {
        return _refCount;
    }

    public void run() {
        if (log.isInfoEnabled()) log.info("ReposSocketServer is running.");
        while (!isShutdown()) {
            try {
                synchronized (_lockObject) {
                    if (log.isInfoEnabled()) log.info("SocketServer is waiting for connections.");
                    Socket server = listener.accept();
                    SocketThread thread = new SocketThread(server); // need to pass client input/output socket stream also
                    SocketThread.setShutdown(isShutdown());
                    thread.start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
